import { createI18n } from 'vue-i18n';
import { Message, Language } from '@/constants/local';
import { storage, getStorageByPrefix } from '@/util/common';

class Locale {

  i18n: any;
  local = 'zhCn'

  constructor() {
    this.i18n = this.createI18nInstance();
  }

  getClientLocal = ():string => {
    const st = getStorageByPrefix('m-design');
    return st.get('locale') || 'zhCn';
  }

  localeTrans = (key: string) => {
    return this.local === 'en' ? Message.en[key] : Message.zhCn[key]; // 默认中文
  }

  setLocal(local: string) {
    this.local = local;
    if (this.i18n) {
      this.i18n.global.locale = local as Language;
    }
  } 

  createI18nInstance() {
    return createI18n({
      locale: this.local,
      fallbackLocale: 'zhCn',
      formatFallbackMessages: true,
      datetimeFormats: {},
      numberFormats: {},
      silentTranslationWarn: true,
      silentFallbackWarn: true,
      messages: Message,
      legacy: false,
    });
  }
}

export default Locale;